package baidu.webapi.impl;

import baidu.webapi.LBSApi;
import baidu.webapi.model.AddressComponent;
import baidu.webapi.utils.HttpUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * Created by xiao.lai on 2015/7/12.
 */
public class BaiduLBS implements LBSApi {

    //日志
    private static Logger logger = LoggerFactory.getLogger(BaiduLBS.class);

    //默认百度ak值
    private static String ak = "fU9CYBpAUd9aq26GsVK5smvv";
    //默认目的地
    private static String direction = "附近";
    //默认最近距离
    private static String distance = "0";
    //默认国家
    private static String country = "中国";
    //默认国家代码
    private static Integer countryCode = 0;

    public static void main(String[] args) throws IOException {

        LBSApi lbsApi = new BaiduLBS();
        AddressComponent addressComponent = lbsApi.getAddressComponentByLatAndLng(40.548397, 110.04701);
        System.out.println("addressComponent" + addressComponent);


    }

    /**
     * 根据经纬度获取详细的地址
     *
     * @param lat   纬度
     * @param lng   经度
     * @return AddressComponent对象
     * */
    @Override
    public AddressComponent getAddressComponentByLatAndLng(double lat, double lng)  {

        String url = "http://api.map.baidu.com/geocoder/v2/?location=" + lat + ","
                + lng + "&output=json&ak=" + ak +"&pois=0";
        JSONObject addressComponentObject = JSONObject.fromObject(HttpUtil.getRequest(url))
                .getJSONObject("result").getJSONObject("addressComponent");
        /**
         * 初始化相关参数
         * */
        AddressComponent addressComponent = new AddressComponent();
        if (addressComponentObject != null) {
            addressComponent.setProvince(addressComponentObject.getString("province"));
            addressComponent.setCity(addressComponentObject.getString("city"));
            addressComponent.setDistrict(addressComponentObject.getString("district"));
            addressComponent.setStreet(addressComponentObject.getString("street"));
            addressComponent.setStreet_number(addressComponentObject.getString("street_number"));
            //调用默认信息
            addressComponent.setCountry(addressComponentObject.getString("country"));
            addressComponent.setCountry_code(addressComponentObject.getInt("country_code"));
            addressComponent.setDistance(distance);
            addressComponent.setDirection(direction);
        }else {
            addressComponent = null;
        }
        return addressComponent;
    }
}
